#include <cstdlib>
#include <unistd.h>
#include <stdio.h>
#include "master.h"
#include "debug.h"

Master *master = NULL;

int main(int argc, char **argv)
{
	init_debug_levels(SECTION_MASTER, 20);

	int ch;
	int ret = 0;
	uint64_t id;
	string conf;

	while ((ch = getopt(argc, argv, "i:c:h")) != -1) {
		switch (ch) {
		case 'i':
			id = atoi(optarg);
			break;
		case 'c':
			conf = strdup(optarg);
			break;
		case 'h':
			debug(SECTION_MASTER, 10, "\n-i Master ID\n-c DSS Configure File Name\n-h Help\n");
			return ret;
		default:
			debug(SECTION_MASTER, 10, "NOT recognized option: %c", ch);
			debug(SECTION_MASTER, 10, "\n-i Master ID\n-c DSS Configure File Name\n-h Help\n");
			return ret;
		}
	}
	master = new Master(id, conf);
	/* init master from configure file */
	if (0 != master->parse_conf()) {
		debug(SECTION_MASTER, 10, "parse configure file err\n");
		return ret;
	}
	/* start heartbeat thread */
	//pthread_create(&(master->heartbeat_th), 0, Master::heartbeat_main, master);

	/* rpc ... prepare */
	master->prepare();

	/* accept rpc connection and request */
	clock_t now, last_active, last_heartbeat;
	now = clock();
	last_active = now;
	//last_heartbeat = now - master->heartbeat_interval;
	last_heartbeat = now;

	while(master->state == ACTIVE)
	{
		now = clock();
		if (((float)(now - last_heartbeat) / CLOCKS_PER_SEC) > master->heartbeat_interval) {
			master->heartbeat_manager();
      last_heartbeat = now;
    }
		if (((float)(now - last_active) / CLOCKS_PER_SEC) > 1.0) {
			master->rpc_server->AcceptSess();
      last_active = now;
    }
		
		master->rpc_server->RpcServerHandleRx();
		master->rpc_server->RpcServerHandleTx();
		master->rpc_client->RpcCliHandleRx();
		master->rpc_client->RpcCliHandleTx();
  }

	//TODO exit
//	pthread_join(master->heartbeat_th, NULL); //need move in master_exit()
	master->exit();
	return 0;
}










